package com.demo.resourcecode.validator;

import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DirectFieldBindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.SmartValidator;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.demo.resourcecode.validator.Person.Simple;

@RestController
public class ValidController {

	public ValidController() {
		System.out.println("");
	}

	@Autowired
    private SmartValidator smartValidator;
	@Autowired
	private ApplicationContext applicationContext;

	@PostMapping("/valid")
	public String valid(@RequestBody @Validated({Simple.class}) Person p, BindingResult result){
		//applicationContext.getBeanNamesForType(Validator.class);
		//applicationContext.getBean("api.validatorFactory");
		//applicationContext.getBean("api.validator");
		System.out.println(result.getErrorCount());
		Person person = new Person();
        person.setAge(-1);
        person.setStart(DateUtils.addDays(new Date(), 1));

        Errors errors = new DirectFieldBindingResult(person, "person");
        ValidationUtils.invokeValidator(smartValidator, person, errors, Person.Complex.class);
        System.out.println(errors);
        return "valid";
	}

}
